//
//  HomeReleaseViewController.m
//  ioschishan
//
//  Created by 马田成 on 2017/8/1.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "HomeReleaseViewController.h"
#import "HomeLookNowViewController.h"
#import "HomeWaterNowViewController.h"

#import "AFNetworking.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"
#import <Availability.h>





#define HeightVC [UIScreen mainScreen].bounds.size.height//获取设备高度
#define WidthVC [UIScreen mainScreen].bounds.size.width//获取设备宽度

@interface HomeReleaseViewController ()<UITextViewDelegate, numDelegate>{
    
    float buttonHeight;//图片高度
    NSString *water_num;//水滴总数
    NSString *collar_num;//可领次数
}

@property (nonatomic, strong) UILabel *placeHolderLabel;
@property (nonatomic, strong) UITextView *evaluateTF;//发布内容
@property(nonatomic,strong) UIScrollView *mianScrollView;
@property (nonatomic, strong) UIButton *buttonWater;//赏水滴
@property (nonatomic, strong) UIButton *buttonPublicity;//公开

@property (nonatomic,strong) NSMutableArray * photoArr;
@end

@implementation HomeReleaseViewController
- (void)viewWillAppear:(BOOL)animated{
    
    if ([[self getBigImageArray] count] < 3) {
        
        buttonHeight = ([UIScreen mainScreen].bounds.size.width - screenScale(45)) / 3;
        
    }else if ([[self getBigImageArray] count] < 6){
        
        buttonHeight = ([UIScreen mainScreen].bounds.size.width  - screenScale(45)) / 3 * 2 + screenScale(30);
        
    }else{
        
        buttonHeight = ([UIScreen mainScreen].bounds.size.width  - screenScale(45)) + screenScale(30);
        
    }
    
    self.buttonWater.frame = CGRectMake(15,buttonHeight + screenScale(130), 80, 24);
   
    self.buttonPublicity.frame =CGRectMake(DEF_SCREEN_WIDTH - 95,buttonHeight + screenScale(130), 80, 24);
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creationView];
    
    // Do any additional setup after loading the view.
}
- (void)getWater:(NSString *)water andNum:(NSString *)num{

    if ([water length] == 0) {
        [self.buttonWater setTitle:@"+水滴" forState:UIControlStateNormal];
    }else {
    
        NSString *str1 = @"赏";
        NSString *str2 = [[[[[str1 stringByAppendingString:water] stringByAppendingString:@"水滴"] stringByAppendingString:@"/"] stringByAppendingString:num] stringByAppendingString:@"次"];
        
        [self.buttonWater setTitle:str2 forState:UIControlStateNormal];
        
    }
    water_num = water;
    collar_num = num;
    
    

}
- (void)creationView{

    
    [self setTitle:@"发布"];
    UIView *threadView = [[UIView alloc]initWithFrame:CGRectMake(0, screenScale(1), scrWidth(), screenScale(0.7))];
    threadView.backgroundColor = getColor(@"cccccc");
    [self.view addSubview:threadView];
    UIButton *buttonAdd = [[UIButton alloc] init];
    
    buttonAdd.frame = CGRectMake(DEF_SCREEN_WIDTH - 50, 0, 40, 40);
    [buttonAdd setTitle:@"发布" forState:UIControlStateNormal];
    [buttonAdd setTitleColor:getColor(@"3A95FF") forState:UIControlStateNormal];
    
    [buttonAdd addTarget:self action:@selector(ReleaseClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc]initWithCustomView:buttonAdd];
    self.navigationItem.rightBarButtonItem = rightItme;
    
    self.evaluateTF = [[UITextView alloc] init];
    [self.view addSubview:self.evaluateTF];
    self.evaluateTF.font = [UIFont systemFontOfSize:13];
    
    [self.evaluateTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(15);
        make.left.equalTo(self.view).with.offset(15);
        make.right.equalTo(self.view).with.offset(-15);
        make.height.offset(90);
        
    }];
    
    self.placeHolderLabel = [[UILabel alloc] init];
    
    self.placeHolderLabel.numberOfLines = 0;
    self.placeHolderLabel.font = [UIFont systemFontOfSize:13];
    self.placeHolderLabel.textColor = getColor(@"9B9B9B");
    [self.placeHolderLabel sizeToFit];
    self.placeHolderLabel.text = @"来和大家一起分享点什么吧～";
    self.evaluateTF.delegate = self;
    
    
    [self.evaluateTF addSubview:self.placeHolderLabel];
    
    [self.evaluateTF setValue:self.placeHolderLabel forKey:@"_placeholderLabel"];
    
    _mianScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, screenScale(120), WidthVC, HeightVC+530)];
    _mianScrollView.contentSize = CGSizeMake(WidthVC, HeightVC+530);
    _mianScrollView.bounces = YES;
    _mianScrollView.showsVerticalScrollIndicator = false;
    _mianScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_mianScrollView];
    [_mianScrollView setDelegate:self];
    self.showInView = _mianScrollView;
    self.maxCount = 9;
    
    UIView *view = [[UIView alloc] init];
    [self.view addSubview:view];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.height.offset(DEF_SCREEN_HEIGHT - 120 - 138 - (DEF_SCREEN_WIDTH-100));
    }];
    view.backgroundColor = [UIColor whiteColor];
    [self initPickerView];
    
    //水滴
    self.buttonWater = [[UIButton alloc] init];
    [self.view addSubview:self.buttonWater];
    [self.buttonWater mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(165+104);
        make.left.equalTo(self.view).with.offset(15);
        make.height.offset(24);
        
    }];
    self.buttonWater.backgroundColor = getColor(@"F5F5F5");
    [self.buttonWater setTitle:@"+水滴" forState:UIControlStateNormal];
    [self.buttonWater setTitleColor:getColor(@"4A4A4A") forState:UIControlStateNormal];
    self.buttonWater.titleLabel.font = [UIFont systemFontOfSize:12];
    [_buttonWater addTarget:self action:@selector(waterClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
//    //公开
//    self.buttonPublicity = [[UIButton alloc] init];
//    [self.view addSubview:self.buttonPublicity];
//    self.buttonPublicity.frame = CGRectMake(DEF_SCREEN_WIDTH - 95,120 +screenScale(30), 80, 24);
//    self.buttonPublicity.backgroundColor = getColor(@"F5F5F5");
//    [self.buttonPublicity setTitle:@"公开" forState:UIControlStateNormal];
//    [self.buttonPublicity setTitleColor:getColor(@"4A4A4A") forState:UIControlStateNormal];
//    self.buttonPublicity.titleLabel.font = [UIFont systemFontOfSize:12];
//     [_buttonPublicity addTarget:self action:@selector(PublicityClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    

}
//发布
- (void)ReleaseClick{
    
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在上传...";
    //是否有遮罩
    hud.dimBackground = YES;

    
    
    

    self.photoArr = [[NSMutableArray alloc] initWithArray:[self getBigImageArray]];
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue:token forKey:@"token"];
    if ([self.evaluateTF.text length] == 0) {
        [PublicFunction showAlert:nil message:@"内容不能为空" duration:10.0f];
        
    }else {
    
        [productParams setValue:self.evaluateTF.text forKey:@"content"];
        
    }
    [productParams setValue:water_num forKey:@"water_num"];
    [productParams setValue:collar_num forKey:@"collar_num"];
    [productParams setValue:@"1" forKey:@"type"];

    //两种方式上传头像
    /*方式一：使用NSData数据流传图片*/
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/plain",
                                                         @"text/javascript",
                                                         @"text/json",
                                                         @"text/html",
                                                         @"image/jpeg", nil];
    [manager POST:home_CircleAdd parameters:productParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(self.photoArr){
            __block NSInteger i = 0;
            [self.photoArr enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                //压缩图片
                i++;
                // NSData *imageData = UIImagePNGRepresentation(obj);
                NSData *imageData = UIImageJPEGRepresentation(obj,0.005);
                
                
                //压缩图片
                
                //拼接图片名称+时间确保不重复命名
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.jpg", [formatter stringFromDate:[NSDate date]],i];
                // 测试输出文件名
                
                //上传图片，以文件流的格式

                [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"image%ld",i] fileName:imageFileName mimeType:@"image/JPG"];
                
                
            }];
        }

        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *strtmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *requestTmp = [NSString stringWithString: strtmp];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];  //解析
        
         [hud removeFromSuperview];
        
        [self.navigationController popToRootViewControllerAnimated:YES];

        NSLog(@"+++>%@", resultDic);
        
        NSLog(@"--->%@", resultDic[@"msg"]);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        [hud removeFromSuperview];
        NSLog(@"--->%@", error);
    }];

    
    
}
//谁可以看
- (void)PublicityClick{

    HomeLookNowViewController *vc = [[HomeLookNowViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
}
//水滴
- (void)waterClick{

    HomeWaterNowViewController *vc = [[HomeWaterNowViewController alloc] init];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
